module.exports = function(app) {
	return new Handler(app);
};

var Handler = function(app) {
	this.app = app;
};

var handler = Handler.prototype;

/**
 * Gate handler that dispatch user to connectors.
 *
 * @param {Object} msg message from client
 * @param {Object} session
 * @param {Function} next next stemp callback
 *
 */
handler.send = function(msg, session, next) {
	//后台服务器。既然到了后台，那么前台session一定有
	var room_id  = session.get('room_id');
	var username = session.uid.split('*')[0];
	var channelService = this.app.get('channelService');
	
	var channel = channelService.getChannel(room_id, false);//不创建

	var route = 'onChat';
	var msgparam = {
		msg    : msg.content,
		from   :username,
		target :msg.target
	}
	
	
	if( msg.target == "*"){
		channel.pushMessage(route, msgparam);
	}

	else{
		var tuid = msg.target + '*' + room_id;
		var tsid = channel.getMember(tuid)['sid'];// 
		channelService.pushMessageByUids(route, msgparam, [{
			uid:tuid,
			sid:tsid
		}])
	}




	next(null, {route: route});
};